<template>
    <div class="student-list">
        <el-card shadow="hover">
            <template #header>
                <div class="card-header">
                    <span class="title">学生列表</span>
                    <div class="header-actions">
                        <el-button type="success" @click="handleDownloadTemplate">
                            <el-icon>
                                <Download />
                            </el-icon>
                            下载模板
                        </el-button>
                        <el-upload
                            ref="uploadRef"
                            :action="uploadAction"
                            :headers="uploadHeaders"
                            :show-file-list="false"
                            :before-upload="beforeUpload"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :on-progress="handleUploadProgress"
                            accept=".xlsx,.xls"
                        >
                            <el-button type="warning">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                导入Excel
                            </el-button>
                        </el-upload>
                        <el-button type="info" @click="handleExport">
                            <el-icon>
                                <Download />
                            </el-icon>
                            导出数据
                        </el-button>
                        <el-button
                            type="danger"
                            plain
                            @click="handleBatchDelete"
                            :disabled="selectedRows.length === 0"
                        >
                            <el-icon>
                                <Delete />
                            </el-icon>
                            批量删除 ({{ selectedRows.length }})
                        </el-button>
                        <el-button type="primary" @click="handleAdd">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            添加学生
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 搜索区域 -->
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="学号">
                    <el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label="班级">
                    <el-select
                        v-model="searchForm.className"
                        placeholder="请选择班级"
                        clearable
                        style="width: 200px"
                    >
                        <el-option label="全部" value="" />
                        <el-option
                            v-for="cls in classList"
                            :key="cls.className"
                            :label="cls.className"
                            :value="cls.className"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="宿舍">
                    <el-input v-model="searchForm.dormitory" placeholder="请输入宿舍号" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button @click="handleReset">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                    <el-button
                        type="warning"
                        plain
                        @click="handleAllocateDormitory"
                        :loading="allocating"
                    >
                        <el-icon>
                            <HomeFilled />
                        </el-icon>
                        自动分配宿舍
                    </el-button>
                </el-form-item>
            </el-form>

            <!-- 表格 -->
            <el-table
                :data="tableData"
                style="width: 100%"
                v-loading="loading"
                border
                max-height="calc(100vh - 350px)"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="studentId" label="学号" width="120" />
                <el-table-column prop="name" label="姓名" width="150" />
                <el-table-column prop="gender" label="性别" width="120" />
                <el-table-column prop="className" label="班级" width="250" />
                <el-table-column prop="teacherName" label="班主任" width="150" />
                <el-table-column prop="major" label="专业" width="200" />
                <el-table-column prop="dormitory" label="宿舍" width="150" />
                <el-table-column prop="bedNumber" label="床位号" width="120" />
                <el-table-column prop="building" label="楼栋" width="150" />
                <el-table-column prop="phone" label="联系电话" width="150" />
                <el-table-column label="状态" width="150">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '已入住' ? 'success' : 'warning'">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" text @click="handleEdit(scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" text @click="handleDelete(scope.row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                class="pagination"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </el-card>

        <!-- 添加/编辑学生弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="700px"
            :close-on-click-modal="false"
            @close="handleDialogClose"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="100px"
                class="student-form"
            >
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="学号" prop="studentId">
                            <el-input
                                v-model="form.studentId"
                                placeholder="请输入学号"
                                :disabled="isEdit"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="form.name" placeholder="请输入姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="性别" prop="gender">
                            <el-radio-group v-model="form.gender">
                                <el-radio label="男">男</el-radio>
                                <el-radio label="女">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="班级" prop="className">
                            <el-select
                                v-model="form.className"
                                placeholder="请选择班级"
                                style="width: 100%"
                                filterable
                                @change="handleClassChange"
                            >
                                <el-option
                                    v-for="cls in classList"
                                    :key="cls.className"
                                    :label="cls.className"
                                    :value="cls.className"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="班主任">
                            <el-input
                                v-model="form.teacherName"
                                placeholder="请先选择班级"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="专业">
                            <el-input v-model="form.major" placeholder="请先选择班级" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="phone">
                            <el-input
                                v-model="form.phone"
                                placeholder="请输入联系电话（选填）"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="楼栋">
                            <el-select
                                v-model="form.building"
                                placeholder="请选择楼栋（选填）"
                                style="width: 100%"
                                filterable
                                clearable
                                @change="handleBuildingChange"
                            >
                                <el-option
                                    v-for="building in buildingList"
                                    :key="building.buildingName"
                                    :label="building.buildingName"
                                    :value="building.buildingName"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="宿舍号">
                            <el-select
                                v-model="form.dormitory"
                                placeholder="请先选择楼栋（选填）"
                                style="width: 100%"
                                filterable
                                clearable
                                :disabled="!form.building"
                            >
                                <el-option
                                    v-for="dorm in dormitoryList"
                                    :key="dorm.roomNumber"
                                    :label="dorm.roomNumber"
                                    :value="dorm.roomNumber"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="床位号">
                            <el-input
                                v-model="form.bedNumber"
                                placeholder="请输入床位号（选填）"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-select
                                v-model="form.status"
                                placeholder="请选择状态（选填）"
                                style="width: 100%"
                                clearable
                            >
                                <el-option label="已入住" value="已入住" />
                                <el-option label="待入住" value="待入住" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="备注">
                    <el-input
                        v-model="form.remark"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入备注信息"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 上传进度对话框 -->
        <el-dialog
            v-model="uploadVisible"
            title="导入学生数据"
            width="400px"
            :close-on-click-modal="false"
            :show-close="false"
        >
            <div style="text-align: center; padding: 20px">
                <el-progress :percentage="uploadProgress" :stroke-width="15" />
                <p style="margin-top: 20px; color: #666">正在上传文件，请稍候...</p>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Plus,
    Search,
    Refresh,
    Edit,
    Delete,
    Download,
    Upload,
    HomeFilled,
} from '@element-plus/icons-vue'
import {
    getStudentList,
    addStudent,
    updateStudent,
    deleteStudent,
    batchDeleteStudents,
    downloadStudentTemplate,
    exportStudents,
    allocateDormitory,
} from '@/api/student'
import { getAllClasses } from '@/api/class'
import { getBuildingList } from '@/api/building'
import { getDormitoryList } from '@/api/dormitory'
import { useAuthStore } from '@/stores/auth'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = ref({
    studentId: '',
    name: '',
    className: '',
    dormitory: '',
})

// 上传相关
const authStore = useAuthStore()
const uploadRef = ref(null)
const uploadAction = computed(() => {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9001/api'
    return `${baseURL}/student/import`
})
const uploadHeaders = computed(() => ({
    Authorization: `Bearer ${authStore.token}`,
    token: authStore.token,
}))
const uploadProgress = ref(0)
const uploadVisible = ref(false)

// 自动分配宿舍相关
const allocating = ref(false)

// 班级数据（从后端获取）
const classList = ref([])

// 楼栋数据（从后端获取）
const buildingList = ref([])

// 宿舍数据（根据楼栋动态获取）
const dormitoryList = ref([])

// 表格数据
const tableData = ref([])
const selectedRows = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const currentEditIndex = ref(-1)

const dialogTitle = computed(() => {
    return isEdit.value ? '编辑学生' : '添加学生'
})

const form = ref({
    studentId: '',
    name: '',
    gender: '男',
    age: 18,
    className: '',
    teacherName: '',
    major: '',
    phone: '',
    building: '',
    dormitory: '',
    bedNumber: '',
    status: '待入住',
    remark: '',
})

const rules = {
    studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    className: [{ required: true, message: '请选择班级', trigger: 'change' }],
    phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
}

// 班级选择改变时的处理
const handleClassChange = (className) => {
    const selectedClass = classList.value.find((cls) => cls.className === className)
    if (selectedClass) {
        form.value.teacherName = selectedClass.teacherName
        form.value.major = selectedClass.major
    } else {
        form.value.teacherName = ''
        form.value.major = ''
    }
}

// 重置表单
const resetForm = () => {
    form.value = {
        studentId: '',
        name: '',
        gender: '男',
        age: 18,
        className: '',
        teacherName: '',
        major: '',
        phone: '',
        building: '',
        dormitory: '',
        bedNumber: '',
        status: '待入住',
        remark: '',
    }
}

// 获取学生列表
const fetchStudentList = async () => {
    loading.value = true
    try {
        const params = {
            page: currentPage.value,
            pageSize: pageSize.value,
            ...searchForm.value,
        }
        const res = await getStudentList(params)
        if (res.code === 200 || res.code === 0) {
            tableData.value = res.data.list || res.data
            total.value = res.data.total || 0
        }
    } catch (error) {
        console.error('获取学生列表失败:', error)
        // 如果接口失败，使用模拟数据
        tableData.value = [
            {
                id: 1,
                studentId: '2023001',
                name: '张三',
                gender: '男',
                age: 20,
                className: '计科2023-1班',
                teacherName: '张明',
                major: '计算机科学与技术',
                dormitory: '101',
                building: 'A栋',
                phone: '13800138001',
                status: '已入住',
                remark: '',
            },
            {
                id: 2,
                studentId: '2023002',
                name: '李四',
                gender: '女',
                age: 19,
                className: '软工2023-1班',
                teacherName: '王强',
                major: '软件工程',
                dormitory: '102',
                building: 'A栋',
                phone: '13800138002',
                status: '已入住',
                remark: '',
            },
        ]
        total.value = tableData.value.length
    } finally {
        loading.value = false
    }
}

// 获取班级列表
const fetchClassList = async () => {
    try {
        const res = await getAllClasses()
        if (res.code === 200 || res.code === 0) {
            classList.value = res.data || []
        }
    } catch (error) {
        console.error('获取班级列表失败:', error)
        // 使用模拟数据
        classList.value = [
            { className: '计科2023-1班', teacherName: '张明', major: '计算机科学与技术' },
            { className: '计科2023-2班', teacherName: '李华', major: '计算机科学与技术' },
            { className: '软工2023-1班', teacherName: '王强', major: '软件工程' },
            { className: '网工2023-1班', teacherName: '赵丽', major: '网络工程' },
            { className: '信安2023-1班', teacherName: '陈刚', major: '信息安全' },
            { className: '数科2023-1班', teacherName: '刘敏', major: '数据科学与大数据技术' },
        ]
    }
}

// 获取楼栋列表
const fetchBuildingList = async () => {
    try {
        const res = await getBuildingList({ page: 1, pageSize: 999 })
        if (res.code === 200 || res.code === 0) {
            buildingList.value = res.data.list || res.data || []
        }
    } catch (error) {
        console.error('获取楼栋列表失败:', error)
        // 使用模拟数据
        buildingList.value = [
            { buildingName: 'A栋' },
            { buildingName: 'B栋' },
            { buildingName: 'C栋' },
            { buildingName: 'D栋' },
        ]
    }
}

// 根据楼栋获取宿舍列表
const fetchDormitoryListByBuilding = async (building) => {
    if (!building) {
        dormitoryList.value = []
        return
    }

    try {
        const res = await getDormitoryList({
            page: 1,
            pageSize: 999,
            building: building,
        })
        if (res.code === 200 || res.code === 0) {
            dormitoryList.value = res.data.list || res.data || []
        }
    } catch (error) {
        console.error('获取宿舍列表失败:', error)
        // 使用模拟数据
        dormitoryList.value = [
            { roomNumber: '101' },
            { roomNumber: '102' },
            { roomNumber: '103' },
            { roomNumber: '201' },
            { roomNumber: '202' },
            { roomNumber: '203' },
        ]
    }
}

// 楼栋变化时的处理
const handleBuildingChange = (building) => {
    // 清空宿舍号和床位
    form.value.dormitory = ''
    form.value.bedNumber = ''
    // 获取该楼栋下的宿舍列表
    fetchDormitoryListByBuilding(building)
}

// 添加学生
const handleAdd = () => {
    resetForm()
    isEdit.value = false
    dormitoryList.value = [] // 清空宿舍列表
    dialogVisible.value = true
}

// 编辑学生
const handleEdit = (row) => {
    isEdit.value = true
    currentEditIndex.value = row.id
    form.value = { ...row }
    // 如果有楼栋信息，加载该楼栋的宿舍列表
    if (row.building) {
        fetchDormitoryListByBuilding(row.building)
    }
    dialogVisible.value = true
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 批量删除学生
const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 个学生吗？删除后将无法恢复！`,
            '批量删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                distinguishCancelAndClose: true,
            },
        )

        const ids = selectedRows.value.map((row) => row.id)
        const res = await batchDeleteStudents(ids)

        if (res.code === 200 || res.code === 0) {
            ElMessage.success(res.message || `批量删除成功，共删除 ${ids.length} 条数据`)
            selectedRows.value = []
            fetchStudentList()
        } else {
            ElMessage.error(res.message || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
            console.error('批量删除学生失败:', error)
            ElMessage.error(error.message || '批量删除失败')
        }
    }
}

// 删除学生
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要删除学生 ${row.name} 吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })

        const res = await deleteStudent(row.id)
        if (res.code === 200 || res.code === 0) {
            ElMessage.success('删除成功')
            fetchStudentList() // 重新加载列表
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除学生失败:', error)
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                if (isEdit.value) {
                    // 编辑
                    const res = await updateStudent(currentEditIndex.value, form.value)
                    if (res.code === 200 || res.code === 0) {
                        ElMessage.success('修改成功')
                        dialogVisible.value = false
                        fetchStudentList() // 重新加载列表
                    }
                } else {
                    // 添加
                    const res = await addStudent(form.value)
                    if (res.code === 200 || res.code === 0) {
                        ElMessage.success('添加成功')
                        dialogVisible.value = false
                        fetchStudentList() // 重新加载列表
                    }
                }
            } catch (error) {
                console.error('提交失败:', error)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 弹窗关闭时重置表单
const handleDialogClose = () => {
    formRef.value?.resetFields()
    resetForm()
    currentEditIndex.value = -1
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchStudentList()
}

// 重置搜索
const handleReset = () => {
    searchForm.value = {
        studentId: '',
        name: '',
        className: '',
        dormitory: '',
    }
    handleSearch()
}

// 分页
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchStudentList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchStudentList()
}

// 下载导入模板
const handleDownloadTemplate = async () => {
    try {
        await downloadStudentTemplate()
        ElMessage.success('模板下载成功')
    } catch (error) {
        console.error('下载模板失败:', error)
        ElMessage.error('下载模板失败')
    }
}

// 上传前校验
const beforeUpload = (file) => {
    const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isExcel) {
        ElMessage.error('只能上传 Excel 文件！')
        return false
    }
    if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB！')
        return false
    }

    uploadProgress.value = 0
    uploadVisible.value = true
    return true
}

// 上传进度
const handleUploadProgress = (event) => {
    uploadProgress.value = Math.round((event.loaded / event.total) * 100)
}

// 上传成功
const handleUploadSuccess = (response) => {
    uploadVisible.value = false
    if (response.code === 200 || response.code === 0) {
        ElMessage.success(response.message || '导入成功')
        fetchStudentList() // 刷新列表
    } else {
        ElMessage.error(response.message || '导入失败')
    }
}

// 上传失败
const handleUploadError = (error) => {
    uploadVisible.value = false
    console.error('上传失败:', error)
    ElMessage.error('导入失败，请检查文件格式')
}

// 导出数据
const handleExport = async () => {
    try {
        await exportStudents(searchForm.value)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 自动分配宿舍
const handleAllocateDormitory = async () => {
    try {
        await ElMessageBox.confirm(
            '确定要执行自动分配宿舍吗？系统将为所有未分配宿舍的学生自动分配，分配规则：同班级同性别优先、最多3个班级混住。',
            '自动分配宿舍',
            {
                confirmButtonText: '确定分配',
                cancelButtonText: '取消',
                type: 'warning',
                distinguishCancelAndClose: true,
            },
        )

        allocating.value = true

        const res = await allocateDormitory()

        if (res.code === 200 || res.code === 0) {
            const result = res.data

            // 显示详细的分配结果
            await ElMessageBox.alert(
                `<div style="line-height: 1.8;">
                    <p><strong>分配完成！</strong></p>
                    <p>总学生数：<strong>${result.totalCount}</strong> 人</p>
                    <p style="color: #67C23A;">成功分配：<strong>${result.successCount}</strong> 人</p>
                    <p style="color: #F56C6C;">分配失败：<strong>${result.failCount}</strong> 人</p>
                    <p>成功率：<strong>${result.successRate}</strong></p>
                    ${result.failCount > 0 ? '<p style="color: #E6A23C; margin-top: 10px;">提示：部分学生分配失败可能是因为宿舍数量不足或没有合适的宿舍</p>' : ''}
                </div>`,
                '分配结果',
                {
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: '确定',
                    type: result.failCount === 0 ? 'success' : 'warning',
                },
            )

            // 刷新学生列表
            fetchStudentList()
        } else {
            ElMessage.error(res.message || '分配失败')
        }
    } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
            console.error('自动分配宿舍失败:', error)
            ElMessage.error(error.message || '分配失败')
        }
    } finally {
        allocating.value = false
    }
}

// 初始化数据
onMounted(() => {
    fetchClassList()
    fetchBuildingList()
    fetchStudentList()
})
</script>

<style lang="scss" scoped>
.student-list {
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .header-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }
    }

    .search-form {
        margin-bottom: 20px;
    }

    .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .student-form {
        padding: 20px 20px 0;

        :deep(.el-input-number) {
            width: 100%;
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
}
</style>
